<script>
import {createProps} from '@/utils';
import {createField} from '@comp/hhd/design/FormDesigner/types';
import {AuthType} from '@comp/hhd/design/Constants';
import RelationSelectorButton from '@comp/hhd/design/FormEngine/RelationWrapper/RelationSelectorButton.vue';
import {openWindow} from '@/utils/WindowUtils';
import {stop} from '@/utils/FormDesignUtils';

export default {
  name: 'RelationWrapper',
  props: {
    fieldConfig: createProps(Object, createField),
    context: createProps(Object, () => undefined),
    formModel: createProps(Object, () => undefined),
    rowIndex: createProps(Number),
    rowId: createProps(String),
  },
  render(h) {
    if (this.isHide()) return undefined;
    if (this.isBrowse()) return this.renderText();
    return this.renderEdit();
  },
  methods: {
    renderText() {
      if (this.hasRelationData()) {
        return this.wrapperLink(this.getFieldVnode());
      }
      return this.getFieldVnode();
    },
    wrapperLink(vnode) {
      let h = this.$createElement;
      return h('a', {
        class: 'relation-field-link-wrapper',
        on: {
          click: e => this.openRelationWindow() || stop(e),
        }
      }, [vnode]);
    },
    openRelationWindow() {
      let relationData = this.getRelationDataItem();
      if (!relationData) return;
      openWindow(() => ['components/hhd/design/FormRelationView/FormRelationView', {
        props: {
          relationDataId: relationData.id,
          relationDataProp: relationData
        }
      }], {
        title: '管理单据详情',
        key: 'formRelationView',
      });
    },
    hasRelationData() {
      let relationData = this.getRelationData();
      if (!relationData) return;
      let fieldId = this.fieldConfig.id;
      if (!this.rowId) {
        //当前是主表的字段
        return relationData.findIndex(rd => rd.sourceFieldId === fieldId) !== -1;
      } else {
        //当前是明细表字段
        return relationData.findIndex(rd => rd.sourceFieldId === fieldId && rd.sourceSubFormDataId === this.rowId) !== -1;
      }
    },
    getRelationDataItem() {
      let relationData = this.getRelationData();
      if (!relationData) return;
      let fieldId = this.fieldConfig.id;
      if (!this.rowIndex || this.rowIndex === '') {
        //当前是主表的字段
        return relationData.find(rd => rd.sourceFieldId === fieldId);
      } else {
        //当前是明细表字段
        return relationData.find(rd => rd.sourceFieldId === fieldId && rd.sourceSubFormDataId === this.rowId);
      }
    },
    getRelationData() {
      return this.context.formModel && this.context.formModel._relation || [];
    },
    isHide() {
      return this.auth === AuthType.hide;
    },
    isBrowse() {
      return this.auth === AuthType.browse;
    },
    renderEdit() {
      let manualConfigs = this.getManualConfigs();
      if (!manualConfigs || !manualConfigs.length) return this.getFieldVnode(); //没有引用的情况下, 直接渲染原来的节点就行
      let h = this.$createElement;
      return h('div', {class: 'relation-wrapper'}, [
        h('div', {class: 'relation-input-wrapper'}, [this.getFieldVnodeForRelation(manualConfigs)]),
        this.renderButton(manualConfigs)
      ]);
    },
    getFieldVnodeForRelation(manualConfigs) {
      if (this.fieldIsEmpty()) {
        if (!(this.auth === AuthType.edit && this.canEditRelationField(manualConfigs))) {
          return this.createFakeInput();
        }
      } else {
        if (!(this.auth === AuthType.edit && this.canEditRelationField(manualConfigs))) {
          let res = this.getFieldVnode();
          res.componentOptions.propsData.auth = AuthType.browse;
          return this.createFakeInput(res);
        }
      }
      return this.getFieldVnode();
    },
    canEditRelationField(manualConfigs) {
      for (let i = 0; i < manualConfigs.length; i++) {
        let manual = manualConfigs[i].manual;
        if (!manual.manualEditTargetField) {
          return false;
        }
      }
      return true;
    },
    fieldIsEmpty() {
      let value = this.formModel[this.fieldConfig.fieldName];
      return !value;
    },
    createFakeInput(vnode) {
      let relation = this.getRelationDataItem()
      return this.$createElement('div', {
        class: {
          'relation-fake-input': true,
          'relation-fake-input-link': !!vnode && !!relation,
          'relation-fake-input-required': this.formModel._required[this.fieldConfig.fieldName] && !this.formModel[this.fieldConfig.fieldName],
        },
        on: {
          click: () => !!vnode && this.openRelationWindow(),
        }
      }, [vnode || '请选择关联单据']);
    },
    renderButton(manualConfigs) {
      let h = this.$createElement;
      return h(RelationSelectorButton, {
        props: {
          manualConfigs,
          context: this.context,
          formModel: this.context.formModel,
          rowIndex: this.rowIndex,
          rowId: this.rowId
        }
      });
    },
    getManualConfigs() {
      if (!this.context) return undefined;
      let formDefinition = this.context.formDefinition;
      if (!formDefinition) return undefined;
      let res = [], relations = formDefinition.relations || [];
      relations.forEach(r => {
        if (r.relationType === 'manual') {
          let index = r.manuals.findIndex(m => m.manualSelectorFieldId === this.fieldConfig.id);
          if (index !== -1) {
            res.push({manual: r.manuals[index], relation: r});
          }
        }
      });
      return res;
    },
    getFieldVnode() {
      try {
        return this.$slots.default[0];
      } catch (e) {
      }
      return undefined;
    },
  },
  computed: {
    auth() {
      let model = this.formModel || {_auth: {}};
      return model._auth[this.fieldConfig && this.fieldConfig.fieldName || undefined];
    },
  }
};
</script>
<style>
.relation-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

.relation-input-wrapper {
  flex: 1;
}

.relation-field-link-wrapper * {
  display: inline;
}

.relation-field-link-wrapper {
  width: fit-content;
}

.relation-fake-input {
  flex: 1;
  height: 35px;
  border: 1px solid #d9d9d9;
  align-items: center;
  border-radius: 4px;
  display: flex;
  padding: 5px;
  color: #d9d9d9;
}

.relation-fake-input-link {
  cursor: pointer;
  color: #1890ff;
}

.relation-fake-input-required {
  background: #fef0d0;
}
</style>